import os.path
from pathlib import Path

WORKDIR_ROOT = Path.home().joinpath('.aitrader')
WORKDIR_ROOT.mkdir(exist_ok=True, parents=True)
config_file = WORKDIR_ROOT.joinpath('config.toml')

from dataclasses import dataclass, asdict, field
from typing import Any, Dict, List, Optional
import toml

@dataclass
class Config:
    def __init__(self, **kwargs):
        # 只保留已定义的字段
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)

    # 示例配置字段 - 根据你的需求修改这些
    data_dir: str = '' #
    user_token: str = ""
    tq_user = ''
    tq_pwd = ''


    @classmethod
    def from_toml(cls, file_path: str) -> 'Config':
        """从 TOML 文件加载配置"""
        toml_data = toml.load(file_path)
        return cls(**toml_data)

    def to_toml(self, file_path: str) -> None:
        """将配置保存为 TOML 文件"""
        # 确保目录存在
        Path(file_path).parent.mkdir(parents=True, exist_ok=True)

        with open(file_path, 'w') as f:
            toml.dump(asdict(self), f)

    def __str__(self) -> str:
        """以可读格式返回配置"""
        return toml.dumps(asdict(self))


if not config_file.exists():
    Config().to_toml(config_file)

global_config = Config.from_toml(config_file)

data_dir = global_config.data_dir
if not data_dir:
    data_dir = Path.home() / '.aitrader' / '.aitrader_data'
    global_config.data_dir = str(data_dir)
else:
    data_dir = Path(data_dir)
DATA_DIR = data_dir
DATA_DIR.mkdir(exist_ok=True, parents=True)

DATA_ETF_QUOTES = DATA_DIR.joinpath('quotes_etf')
DATA_ETF_QUOTES.mkdir(exist_ok=True, parents=True)


PKG_DATA = Path(os.path.dirname(__file__)).joinpath('data')
DATA_DIR_QUOTES = PKG_DATA.joinpath('quotes')
DATA_DIR_QUOTES.mkdir(exist_ok=True, parents=True)
DATA_TASKS = PKG_DATA.joinpath('tasks')
DATA_TASKS.mkdir(exist_ok=True, parents=True)

DATA_REPORTS = PKG_DATA.joinpath('reports')
DATA_REPORTS.mkdir(exist_ok=True, parents=True)

HOST = 'http://127.0.0.1:5000'
HOST = 'http://www.ailabx.com'



